
package com.starbaba.commActivityStat.view;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.commActivityStat.service.CommActivityStatAppService;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.constant.WebConstants;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.system.user.model.UserVO;
import com.starbaba.util.QueryListUtil;
import com.tuanzi.server.loan_base.model.db.CommProductChannel;
import com.tuanzi.server.loan_base.model.db.CommProductPrdid;
import com.tuanzi.server.loan_base.model.db.credit.PayOrder;
import com.tuanzi.server.loan_base.model.db.stat.StatAppCommActivity;

@SuppressWarnings({"rawtypes","unchecked"})
public class CommActivityStatAppAction extends BaseAction implements ModelDriven<StatAppCommActivity> {

    private static final long serialVersionUID = 1L;
    private StatAppCommActivity model;
	private CommActivityStatAppService commActivityStatAppService;
	private InputStream inputStream;   //导出文件输入流
	private String fileName;   //导出文件名

	public CommActivityStatAppAction(){
		this.commActivityStatAppService = new CommActivityStatAppService();
	}
	
	public String showPage() throws AppException {
		paramsMap=PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		UserVO user = (UserVO) Struts2Utils.getSessionAttribute(WebConstants.SESSION_ATTRIBUTE_USER);
		String userId = user.getUserid();
		// 判断用户是否是合作方
		if(commActivityStatAppService.checkIsPartner(userId)) {
			List<CommProductChannel> channelList = commActivityStatAppService.getPartnetChannel(userId);
			List<CommProductPrdid> prodList = commActivityStatAppService.getProdlList();
			paramsMap.put("channelList", channelList);
			paramsMap.put("prodList", prodList);
		} else {
			List<CommProductChannel> channelList = commActivityStatAppService.getChannelList();
			CommProductChannel channel = new CommProductChannel();
			channel.setChannel_code(-1000);
			channel.setChannel_name("全部");
			channelList.add(channel);
			Collections.reverse(channelList);
			List<CommProductPrdid> prodList = commActivityStatAppService.getProdlList();
			CommProductPrdid product = new CommProductPrdid();
			product.setPrdid(-1000);
			product.setName("全部");
			prodList.add(product);
			Collections.reverse(prodList);
			
			paramsMap.put("channelList", channelList);
			paramsMap.put("prodList", prodList);
		}
		
		return SUCCESS;
	}
	
	

	@Override
	public StatAppCommActivity getModel() {
		if (model==null) {
			model=new StatAppCommActivity();
		}
		return model;
	}
	
	/**
	 * 查询征信订单列表
	 * @throws Exception 
	 */
	public void queryList() throws Exception{
		parsePageRequest();
		PageResponse pageResponse=new PageResponse();
		paramsMap=PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		List list = null;
		int count = 0;
		UserVO user = (UserVO) Struts2Utils.getSessionAttribute(WebConstants.SESSION_ATTRIBUTE_USER);
		String userId = user.getUserid();
		// 判断用户是否是合作方
		if(commActivityStatAppService.checkIsPartner(userId)) {
			String channel = (String) paramsMap.get("channel");
			String prodId = (String) paramsMap.get("prdid");
			if(StringUtils.isEmpty(channel) || StringUtils.isEmpty(prodId)
					|| "-1000".equals(channel) || "-1000".equals(prodId)) {
				sendJsonMessage(JsonUtils.toJson("fail", null, true, null, false));
				return;
			}
			list = commActivityStatAppService.getPartnerDataList(paramsMap, pageRequest.getIDisplayStart(),pageRequest.getIDisplayLength());
			count=commActivityStatAppService.getPartnerCount(paramsMap);
		} else {
			list=commActivityStatAppService.getDataList(paramsMap, pageRequest.getIDisplayStart(),pageRequest.getIDisplayLength());
			count=commActivityStatAppService.getCount(paramsMap);
		}
		pageResponse.setITotalDisplayRecords(count);
		pageResponse.setITotalRecords(count);
		try {
			pageResponse.setAaData(list);
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch(IOException e) {
			LogService.error(e);
		}
	}
	
	/**
	 * 导出数据到excel表格
	 * @return
	 * @throws Exception 
	 */
	public String exportDataList() throws Exception{
		paramsMap=PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
        UserVO user = (UserVO) Struts2Utils.getSessionAttribute(WebConstants.SESSION_ATTRIBUTE_USER);
		String userId = user.getUserid();
		boolean isPartner = commActivityStatAppService.checkIsPartner(userId);
		if(isPartner) {
			String channel = (String) paramsMap.get("channel");
			String prodId = (String) paramsMap.get("prdid");
			if(StringUtils.isEmpty(channel) || StringUtils.isEmpty(prodId)
					|| "-1000".equals(channel) || "-1000".equals(prodId)) {
				sendJsonMessage(JsonUtils.toJson("fail", null, true, null, false));
				return ERROR;
			}
		}
        String result = commActivityStatAppService.exportList(paramsMap, isPartner);
        try {
			  inputStream = new ByteArrayInputStream(result.getBytes("GBK"));
			  fileName = "通用活动统计（APP）" + System.currentTimeMillis() + ".csv";
		} catch (UnsupportedEncodingException e) {
			LogService.error(e);
			return ERROR;
		}
		return SUCCESS;
	}
	
	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}
	
	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	
	
}
